package com.spsoft.security.interceptor.handler;


import com.alibaba.fastjson.JSONArray;
import com.spsoft.core.annotation.AnonymousAccess;
import com.spsoft.core.enums.ResponseEnum;
import com.spsoft.core.exception.AuthException;
import com.spsoft.core.exception.LoginException;
import com.spsoft.core.model.bo.TokenUser;
import com.spsoft.core.utils.Base64;
import com.spsoft.core.utils.DESCrypt;
import com.spsoft.core.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 权限处理器
 *  1.获取token
 *  2.解析token
 *
 * @author cdl
 */
@Component
@Slf4j
public class AuthorityHandlerProcess {

    @Autowired
    private List<AbstractAuthorityHandler> handlers;

    public void process(String token, HttpServletRequest request, AnonymousAccess authority) throws Exception {
        TokenUser tokenUser=null;
        try {
            log.info("请求收到：token:{}",token);
             tokenUser = SecurityUtils.getTokenToUser(token);
            if(tokenUser !=null
                    && tokenUser.getUserCode()!=null
                    && !"".equals(tokenUser.getUserCode())){
                request.setAttribute("tokenUser",tokenUser);
            }else{
                throw new LoginException(ResponseEnum.LOGIN_ERROR);
            }
        }catch (Exception e){
            throw new LoginException(ResponseEnum.LOGIN_ERROR);
        }

        if(authority !=null&&!"".equals(authority.permissionCode())){
            for(AbstractAuthorityHandler handler : handlers) {
                handler.processHandler(tokenUser,request, authority);
            }
        }

    }
}
